package com.grt.condify.common.converter;

import com.grt.condify.utils.StringUtil;

import java.lang.reflect.Field;

/**
 * Created by cy on 16/6/7.
 */
public class FieldStringToFieldConverter implements IConverter<String, Field> {

    private Class<?> clazz;

    public FieldStringToFieldConverter(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Field convert(String value) {
        if (StringUtil.isEmpty(value)) {
            return null;
        }
        do {
            try {
                Field field = clazz.getDeclaredField(value);
                if (field != null) {
                    return field;
                }
            } catch (NoSuchFieldException e) {
                if (clazz.getSuperclass() == null) {
                    return null;
                }
            }
            clazz = clazz.getSuperclass();
        } while (clazz != null);

        return null;
    }
}
